package com.privatbank.userdao;

import com.privatbank.user.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Slava on 12.07.2014.
 */
public class UserDao {

    private final String login;
    private final String password;
    private final String url;

    public UserDao(String login, String password, String url) {
        this.login = login;
        this.password = password;
        this.url = url;
    }

    public void saveUsers(User user) throws SQLException {
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(url, login, password);
            stmt = con.createStatement();
            stmt.executeUpdate("INSERT INTO Users values('" + user.getName() + "')");
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        }
    }

    public List<User> getAll() throws SQLException {
        List<User> users = new ArrayList<User>();
        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            con = DriverManager.getConnection(url, login, password);
            stmt = con.prepareStatement("SELECT * FROM Users");
            rs = stmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setName(rs.getString(1));
                users.add(user);
            }
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        }
        return users;
    }

    public void removeAll() throws SQLException {
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(url, login, password);
            stmt = con.createStatement();
            stmt.executeUpdate("DELETE FROM Users");
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        }
    }

}
